/**
 * Created by XiongXiang on 2017/8/24.
 */
var id = 0;

function nextId() {
    id++;
    return id;
}

function Product(name, manufacturer, price) {
    this.id = nextId();
    this.name = name;
    this.manufacturer = manufacturer;
    this.price = price;
}

var products = [
    new Product('iPhone 7', 'Apple', 6800),
    new Product('Think T440', 'Lenovo', 5999),
    new Product('LBP2900', 'Cannon', 1099)
];

var getProducts = () =>{
    return products;
}

var getProduct = (id) =>{
    var i;
    for (i = 0; i < products.length; i++) {
        if (products[i].id === id) {
            return products[i];
        }
    }
    return null;
}

var createProduct = (name,manufacturer,price) => {
    var p = new Product(name,manufacturer,price);
    products.push(p);
    return p;
}

var deleteProduct = (id)=>{
    var index = -1,
        i;
    for(i = 0;i < products.length; i++){
        if (products[i].id === id){
            index = i;
            break;
        }
    }
    if(index >= 0){
        return products.splice(index,1)[0];
    }
    return null;
}

module.exports = {
    getProducts: getProducts,
    getProduct: getProduct,
    createProduct:createProduct,
    deleteProduct:deleteProduct
}



